import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import Button from '@kuiper-components/button';
import Table from '@knownsec/react-component/dist/Table';
import confirm from '../../../../components/confirm';
import notification from '@kuiper-components/notification';
import EmptyData from '../../../../components/empty/EmptyData';
import fetch from 'API/fetch'

import BindWechat from './BindWechat';
import s from './Wechat.module.css';

// const routePrefix = '/alert/settings/alert-receiver';

export default function Wechat({ className }) {
	const [type, setType] = React.useState('empty')
	const [uid, setUid] = useState(null)
	const [tableData, setTableData] = useState([])
	const [wechat, setWechat] = useState(null)
	const [loading, setLoading] = useState(false)
	const getUserInfo = () => {
		setLoading(true)
		fetch('/api/v2/users/user_info', { method: 'GET' }).then(res => {
			const { uid, wechat } = res.results;
			setUid(uid);
			wechat?.wx_openid &&
				setTableData([{ _id: uid, name: wechat.nickname, updateTime: "" }]);
			setWechat(wechat);
		}).finally(() => {
			setLoading(false)
		})
	}
	React.useEffect(() => {
		if (!loading) setType('img')
	}, [loading])
	useEffect(() => {
		getUserInfo()
	}, [])
	const handleUnbind = () => {
		confirm.warning({
			message: (
				<span>解绑后将不在接收任何告警信息，您确定要解绑该微信吗？</span>
			),
			okText: '解绑',
			cancelText: '取消',
			onOk: () =>
				fetch(`/api/v1/user/${uid}/wechat`, { method: 'DELETE' })
					.then(() => getUserInfo())
					.catch(error => {
						notification.error({
							message: `解绑微信失败`,
							description: error.message,
							placement: 'top',
						});
					}),
		});
	};

	const columns = [
		{
			title: '状态',
			dataIndex: 'name',
			key: 'name',
			render() {
				return (
					<div className={s.actions}>
						绑定成功，您可以通过微信实时接收ScanV推送的所有告警通知。
					</div>
				);
			},
		},
		{
			title: '操作',
			dataIndex: 'enable',
			key: 'actions',
			// eslint-disable-next-line react/display-name
			render(enable, receiver) {
				return (
					<div className={s.actions}>
						<Button primary link className={s.btn} onClick={handleUnbind}>
							解绑
						</Button>
					</div>
				);
			},
		},
	];

	return (
		<div className={cn(className, s.alertReceiver)}>
			<div className={s.toolbox}>
				<BindWechat uid={uid} refetch={getUserInfo}>
					{/* eslint-disable-next-line camelcase */}
					<Button primary disabled={!!wechat?.wx_openid}>
						绑定微信
					</Button>
				</BindWechat>
			</div>
			<div className={s.newtable}>
				<Table
					pro
					columns={columns}
					data={tableData}
					loading={loading}
					empty={<EmptyData type={type} className={s.nobor} />}
				/>
			</div>
		</div>
	);
}

Wechat.propTypes = {
	className: PropTypes.string,
};

Wechat.defaultProps = {
	className: s.Wechat,
};
